import Axios, { AxiosInstance, AxiosRequestConfig } from "axios";
import {
  resultType,
  PureHttpError,
  RequestMethods,
  PureHttpResponse,
  PureHttpRequestConfig
} from "./types.d";
import { useCounterStore } from 'stores/counter';
import { storeToRefs } from 'pinia';
import {useRouter} from "vue-router";

// import qs from "qs";
// import NProgress from "../progress";
// import { loadEnv } from "@build/index";
// import { getToken } from "/@/utils/auth";
// import { useUserStoreHook } from "/@/store/modules/user";

// 加载环境变量 VITE_PROXY_DOMAIN（开发环境）  VITE_PROXY_DOMAIN_REAL（打包后的线上环境）
// const { VITE_PROXY_DOMAIN, VITE_PROXY_DOMAIN_REAL } = loadEnv();

// 相关配置请参考：www.axios-js.com/zh-cn/docs/#axios-request-config-1

const defaultConfig: AxiosRequestConfig = {
  baseURL:"http://192.168.60.206:10019",

  // baseURL:"http://192.168.20.146:10019",
  //   process.env.NODE_ENV === "production"
  //     ? VITE_PROXY_DOMAIN_REAL
  //     : VITE_PROXY_DOMAIN,
  // 当前使用mock模拟请求，将baseURL制空，如果你的环境用到了http请求，请删除下面的baseURL启用上面的baseURL，并将11行、16行代码注释取消
  // baseURL: "",
  timeout: 0, // 默认值是 `0` (永不超时)
  headers: {
    Accept: "application/json, text/plain, */*",
    "Content-Type": "application/json",
    "X-Requested-With": "XMLHttpRequest",
    // "Access-Control-Allow-Origin":"*",
    // "Access-Control-Allow-Headers": "Content-Type",
    // "Access-Control-Allow-Methods": "PUT,POST,GET,DELETE,OPTIONS",
  },
  // 数组格式参数序列化
  // paramsSerializer: params => qs.stringify(params, { indices: false })
};

/**
 * 将所有请求工具和方法都封装在了一个叫PureHttp的类
 * 两个构造函数，在PureHttp创建或者实例化时候被调用：
 * ① 请求拦截 httpInterceptorsRequest ()代码
 * ② 响应拦截 httpInterceptorsResponse ()代码
 * 工具函数
 * ① 通用请求工具函数 request (opens new window)代码
 * ② 单独抽离的 post 工具函数 post (opens new window)代码
 * ③ 单独抽离的 get 工具函数 get
 */
class PureHttp {
  constructor() { //构造器
    this.httpInterceptorsRequest();
    this.httpInterceptorsResponse();
  }


  // 初始化配置对象
  private static initConfig: PureHttpRequestConfig = {};

  // 保存当前Axios实例对象
  private static axiosInstance: AxiosInstance = Axios.create(defaultConfig);

  // 请求拦截
  private httpInterceptorsRequest(): void {
    PureHttp.axiosInstance.interceptors.request.use(
      (config: PureHttpRequestConfig) => {
        const $config = config;
        const store = useCounterStore();
        store.isShow=true
        // 开启进度条动画
        // NProgress.start();

        // 优先判断post/get等方法是否传入回掉，否则执行初始化设置等回掉
        // if (typeof config.beforeRequestCallback === "function") {
        //   config.beforeRequestCallback($config);
        //   return $config;
        // }
        // if (PureHttp.initConfig.beforeRequestCallback) {
        //   console.log("判断post/get等方法是否传入回掉----- YES");
        //   PureHttp.initConfig.beforeRequestCallback($config);
        //   return $config;
        // }
        /**
         * token 过期判断 (opens new window)代码 主要观察 expired，
         * 通过过期时间戳减去当前时间戳，如果大于 0，则说明 token 没有过期，
         * 如果小于等于 0 则 token 过期
         */

        if (sessionStorage.getItem('token')) {
          // 将token放到字典里面，发送给后端
          console.log(  "空参数时,请求拦截会被执行 吗?????" );
          console.log( config.data);
          console.log("请求拦截本地存储s", sessionStorage.getItem("token"));
          config.headers.Authorization =  sessionStorage.getItem('token')
        }else {
          console.log("请求拦截本地存储没有token", sessionStorage.getItem("token"));
        }
        return config;
      },
      error => {
        return Promise.reject(error);
      }
    );
  }

  // 响应拦截
  private httpInterceptorsResponse(): void {

    const instance = PureHttp.axiosInstance;
    instance.interceptors.response.use(
      (response: PureHttpResponse) => {
        const $config = response.config;
        const store = useCounterStore();
        // 关闭进度条动画
        // NProgress.done();
        // store.$reset();
        store.isShow=false
        // 优先判断post/get等方法是否传入回掉，否则执行初始化设置等回掉
        // if (typeof $config.beforeResponseCallback === "function") {
        //   $config.beforeResponseCallback(response);
        //   return response.data;
        // }
        // if (PureHttp.initConfig.beforeResponseCallback) {
        //   PureHttp.initConfig.beforeResponseCallback(response);
        //   return response.data;
        // }
          console.log("response")
          console.log(response)
          console.log(response.status)
          console.log(response.data)

          const     router = useRouter();
        if (response.data.code==456){
          store.msgIsShow=true
          store.msgStr="请先获取权限!"
          // router.push("/home/dashboardFirst")
        }  else if (response.data.code ==789){
          store.msgIsShow=true
          store.msgStr="请先登录!"
          // router.push("/")
        }
        else if (response.data.code !=200){
          store.msgIsShow=true

          if (response.data.code==null){
            store.msgStr= "请开启后端服务器!~"
          }else {
            store.msgStr=response.data
          }
        }
        return response.data;
      },
      (error) => {
       const   router = useRouter();
          const store = useCounterStore();
        const $error = error;
        $error.isCancelRequest = Axios.isCancel($error);
        // 关闭进度条动画
        // NProgress.done();
        // 所有的响应异常 区分来源为取消请求/非取消请求
          console.log("errorerrorerrorerrorerrorerrorerrorerrorerrorerrorerrorerrorerrorerrorerrorerrorerror")
          console.log( error.response.status)
          console.log(error)
          if (error.response.status==456){
              store.msgIsShow=true
              store.msgStr="请先获取权限!"
              // router.push("/home/dashboardFirst")
          }  else if (error.response.status ==789){
              store.msgIsShow=true
              store.msgStr="请先登录!"
              // router.push("/")
          }
          else if (error.response.status !=200){
              store.msgIsShow=true

            if (error.response.data==null){
              store.msgStr= "请开启后端服务器!~"
            }else {
              store.msgStr=error.response.data
            }
          }
        return Promise.reject($error);
      }

    );
  }

  public  mylogin = function (username:string ,
                              password:string ,
                              Mydatabass:string ) {
    return Axios.post('/user/login2', {
      username,
      password,
      Mydatabass
    }).then(
      (res) => {
        return res
      }
    ).catch((err) => {
      console.log(err);
      return err
    })
  }

  // 通用请求工具函数
  public request<T>(
    method: RequestMethods,
    url: string,
    param?: AxiosRequestConfig,
    axiosConfig?: PureHttpRequestConfig
  ): Promise<T> {
    const config = {
      method,
      url,
      ...param,
      ...axiosConfig
    } as PureHttpRequestConfig;

    // 单独处理自定义请求/响应回掉
    return new Promise((resolve, reject) => {
      PureHttp.axiosInstance
        .request(config)
        .then((response: any) => {
          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  }

  // 单独抽离的post工具函数
  public post<T, P>(
    url: string,
    params?: T,
    config?: PureHttpRequestConfig
  ): Promise<P> {
    return this.request<P>("post", url, params, config);
  }

  // 单独抽离的get工具函数
  public get<T, P>(
    url: string,
    params?: T,
    config?: PureHttpRequestConfig
  ): Promise<P> {
    return this.request<P>("get", url, params, config);
  }
}

export const http = new PureHttp();

/**
 *
 *使用方法
 #Get 请求
 import { http } from "/@/utils/http";
 // params传参
 http.request('get', '/xxx', { params: param });
 // url拼接传参
 http.request('get', '/xxx?message=' + msg);

 Post 请求
 // params传参
 http.request('post', '/xxx', { params: param });
 // data传参
 http.request('post', '/xxx', { data: param });
 */

